//
//  JAComposeCell.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/12.
//  Copyright © 2017年 Arvin. All rights reserved.
//

import UIKit

///自定义代理
protocol JAComposeCellDelegate: NSObjectProtocol {
    //添加或替换图片
    func addOrReplaceImage(cell: JAComposeCell)
    //删除图片
    func deleteImage(cell: JAComposeCell)
}

class JAComposeCell: UICollectionViewCell {
    //设置代理属性
    weak var delegate: JAComposeCellDelegate?
    
    var image: UIImage? {
        didSet {
            //如果有图片则显示图片
            if let image = image {
                addOrReplaceButton.setBackgroundImage(image, for: .normal)
                addOrReplaceButton.setBackgroundImage(image, for: .highlighted)
            } else {
                addOrReplaceButton.setBackgroundImage(UIImage(named: "compose_pic_add"), for: .normal)
                addOrReplaceButton.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), for: .highlighted)
            }
            
            //如果image有值, 删除按钮就显示
            deleteButton.isHidden = image == nil        }
    }
    
    ///添加或替换"+"图片的按钮
    lazy var addOrReplaceButton: UIButton = UIButton(title: nil, bgImage: "compose_pic_add", target: self, action: #selector(addOrReplacePicture))
    
    ///删除图片的按钮
     lazy var deleteButton: UIButton = UIButton(title:nil, bgImage: "compose_photo_close", target: self, action: #selector(deletePicture))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension JAComposeCell {
    @objc fileprivate func addOrReplacePicture () {
        
        delegate?.addOrReplaceImage(cell: self)
        
    }
    
    @objc fileprivate func deletePicture() {
        
         delegate?.deleteImage(cell: self)
    }
}

extension JAComposeCell {
    func setupUI () {
        
        //添加"+"按钮图片
        self.contentView.addSubview(addOrReplaceButton)
        //添加删除的按钮图片
        self.contentView.addSubview(deleteButton)
        
        addOrReplaceButton.snp.makeConstraints { (make) in
            make.left.top.equalTo(self).offset(10)
            make.right.bottom.equalTo(self).offset(-10)
            
        }
        
        deleteButton.snp.makeConstraints { (make) in
            make.left.equalTo(self.snp.right).offset(-23)
            make.top.equalTo(self)
        }
     }
}
